// productDetail.js


var request = require("../../requests/api.js");
import util from '../../utils/util.js';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLose: false,
    popuwindowHeight: wx.getSystemInfoSync().windowHeight * 0.75,
    // 产品详情
    product: {},
    productAdditionalImgs: [],
    product_infos: "",
    // secondaryImgs: [{}],
    productTitle: "",
    sellPrice: "",
    originalPrice: "",
    availableStock: "",
    isOversea: false,
    productId: "",
    // 轮播属性
    circular: true,
    interval: 3000,
    autoplay: true,
    indicatorDots: true,
    //所有图片的高度  
    imgheight: 0,
    // 判断商品参数视图折叠的属性
    parametersExpand: true,
    promptExpand: false,
    certificateExpand: false,
    // 规格弹窗属性
    showModalStatus: false,
    animationData: "",
    standardPageHeight: 0,
    productStockTip: "",
    productStatus: "",
    hasStock: "",
    addCartColor: "",
    addCartAble: true,
    addProductNumber: 1,
    addColor: "",
    subColor: "#cccccc",
    // 规格弹窗产品属性
    standard_image: "",
    standard_size: "",
    // sku列表
    products: [{}],
    // 规格列表
    attributes: [{}],
    // 包装的规格组    
    utilAttributes: [],
    // 用来储存选中的规格名
    standardNames: [],
    standardChooseAll: true,
    standardChooseTip: "",

    // 温馨提示
    priceExplain: [] = ["除定制产品、特价产品外，尖叫设计所售产品均提供7天退换货服务。",

      "尖叫设计所售商品均为原创正品，如遇商品签收后发现质量问题，请您签收后24小时内拍照取证并向客服提出反馈，尽快联系客服申请退换货。",

      "单个订单高于¥99元包邮，低于¥99元价格为15元，订单中的多件产品，可能会根据发货期的不同进行合理拆单。拆单所产生的额外配送费将由尖叫设计承担。",

      "客户下单后我们将在72小时内发货，特殊商品具体到货时间依情况有所差异，我们将在您下单后第一时间与您确认。",

      "全国可送（除新疆、西藏、甘肃、青海） 特殊地区（香港、台湾等地）发货与内地发货的邮费计算方式不同，您可于付款前联系客服确认。"
    ],
    // 商品权益
    productQtyInCart: 0

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    new app.WeToast();
    var id = options.productId;
    // id = 12989;
    this.getProductDetail(id);
    // this.getproductComments(id);
    this.getRelatedProducts(id);
  },

  /**
   * 当页面滑动到底部时触发的方法,删掉这个方法后控制台会报事件警告
   */
  onReachBottom: function() {},
  // 获取商品评论
  getproductComments: function(id) {
    var that = this;
    request.getProductComments(id, (res) => {
      var params = "";
      for (var i = 0; i < res.data.productCommentList.length; i++) {
        for (var j = 0; j < res.data.productCommentList[i].specAttributes.length; j++) {
          params = params + res.data.productCommentList[i].specAttributes[j]
        }
        res.data.productCommentList[i].params = params;
      }
      that.setData({
        productCommentList: res.data.productCommentList,
      })

    }, (data) => {

      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }

    }, {})
  },
  //获取相关商品
  getRelatedProducts: function(id) {
    var that = this;
    request.getRelatedProducts(id, (res) => {
      that.setData({
        productVoList: res.data.productVoList
      })
    }, {}, {})
  },
  getProductDetail: function(id) {
    var that = this;
    request.get_productDetails(id, (res) => {
      // console.log(res)
      var productsInCart = app.getProductQtyInCart()
      var trueProduct = res.data
      var infoBigImg = "";
      var infoBigImgHeight = ""

      if (res.data.itemSizeImgVoList != null) {
        if (res.data.itemSizeImgVoList.length > 0) {
          infoBigImg = res.data.itemSizeImgVoList[0].imgUrl
        }
        wx.getImageInfo({
          src: infoBigImg,
          success: function(res) {
            infoBigImgHeight = res.height
            // that.setData({
            //   infoBigImgHeight: infoBigImgHeight,
            // })
          }
        })
      }
      var isHaveSoloGan = that.isHaveSoloGan(res);
      var copyotherInfoVos = that.packOtherInfos(res);
      that.setData({
        infoBigImgHeight: infoBigImgHeight,
        productAdditionalImgs: res.data.productImages,
        infoBigImg: infoBigImg,
        otherInfoVos: copyotherInfoVos,
        parameters: res.data.skuAttrPairs,
        productId: id,
        product: trueProduct,
        productStatus: res.data.productStatus,
        availableStock: res.data.stockQty,
        isHaveSoloGan: isHaveSoloGan

      });
      that.showPopupButton()
      // 获取规格在获取产品信息后
      request.get_productStandard(id, (res) => {
        if (typeof(res.data) == "undefined") {
          that.getDetailSpecific(that.data.productId)
          return
        }
        //找到当前的产品
        var productBean = {}
        for (var i = 0; i < res.data.itemSerialAttributeVoList.length; i++) {
          if (id == res.data.itemSerialAttributeVoList[i].productItemId) {
            productBean = res.data.itemSerialAttributeVoList[i]
          }

        }
        // 包装规格数据
        var attrs = [];
        var attributesLength = 0 //res.data.data.attributes.length
        if (res.data.itemAttrVoList != null) {
          attributesLength = res.data.itemAttrVoList.length
        }

        for (var i = 0; i < attributesLength; i++) {
          var standard = [];
          var utilBean = "";
          for (var j = 0; j < res.data.itemAttrVoList[i].itemAttrValueVoList.length; j++) {
            // 把当前的产品规格设置高亮
            if ((productBean.itemAttrIdPairVoList[i].attributeValueId) == (res.data.itemAttrVoList[i].itemAttrValueVoList[j].attributeValueId)) {
              utilBean = {
                name: res.data.itemAttrVoList[i].itemAttrValueVoList[j],
                state: false,
                checked: true
              }
              that.data.standardNames[i] = res.data.itemAttrVoList[i].itemAttrValueVoList[j].attributeValueId

            } else {
              utilBean = {
                name: res.data.itemAttrVoList[i].itemAttrValueVoList[j],
                state: false,
                checked: false
              }

            }
            standard.push(utilBean)
          }

          attrs.push(standard)
        }
        that.setData({
          products: res.data.itemSerialAttributeVoList,
          attributes: res.data.itemAttrVoList,
          utilAttributes: attrs,
          isLose: false
        })
        that.currentProduct(productBean) // 更新当前页面
        that.resetState(attrs)
      }, {

      }, {});

    }, (res) => {
      if (res.resCode == 40202) {
        that.setData({
          isLose: true
        })
      }
      if (util.alertNetworkError(res)) {
        that.wetoast.toast({
          title: res.resMsg,
        })
      }
    }, () => {})
  },

  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function(res) {
    let product_title = this.data.productTitle
    let product_id = this.data.productId
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title: product_title,
      path: '/pages/product/productDetail?productId=' + product_id,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  //获取当前产品信息
  currentProduct: function(product) {

    wx.reportAnalytics('product_details_page', {
      product_id: product.productId,
      product_name: product.productTitle,
    });
  },

  // 点击产品信息更换大图
  swipclick: function(e) {
    var that = this;
    var current = e.target.dataset.url;
    that.setData({
      infoBigImg: current,
    })

  },
  /**
   * 头图banner点击
   */
  bannerswipclick: function(e) {
    var that = this
    var current = e.target.dataset.url;
    wx.previewImage({
      current: current,
      urls: that.data.productAdditionalImgs,
      success: function() {

      }
    })
  },

  // 点击图文浏览图片
  images: function(e) {
    var that = this;
    var current = e.target.dataset.url;
    var imagesList = [];
    for (var i = 0; i < that.data.product.itemDetailIntroVoList.length; i++) {
      if (that.data.product.itemDetailIntroVoList[i].type == 2) {
        imagesList.push(that.data.product.itemDetailIntroVoList[i].content)
      }
    }
    wx.previewImage({
      current: current,
      urls: imagesList,
      success: function() {

      }
    })
  },

  sku_item_less: function(e) {

    let that = this;
    let current = e.currentTarget.dataset.url;
    let productInfo = this.data.product
    productInfo.productImg = current
    this.setData({
      product: productInfo
    });
  },

  // 点击温馨提示
  productPrompt: function() {
    this.setData({
      promptExpand: !this.data.promptExpand
    })
  },

  // 点击相关证书
  productCertificate: function() {
    this.setData({
      certificateExpand: !this.data.certificateExpand
    })
  },

  // 拨打客服电话
  // service_call: function() {
  //   var csPhone = wx.getStorageSync('csPhone')
  //   wx.makePhoneCall({
  //     phoneNumber: csPhone,
  //     success: function() {},
  //     fail: function() {}
  //   })
  // },
  //侧栏展开
  slideUp: function(e) {
    var animation = wx.createAnimation({
      duration: 300
    });
    animation.translateY('-100%').step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    });

  },

  //侧栏关闭
  slideDown: function(e) {
    var animation = wx.createAnimation({
      duration: 300
    });
    animation.translateY('100%').step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: false
    });
    // 基本信息
    this.getDetailBaseInfo(this.data.productId)
    this.getDetailSkuInfos(this.data.productId)
  },

  // 点击购物车图标
  toShoppingCart: function() {
    if (app.toLogin()) {
      return
    }
    wx.switchTab({
      url: '../../pages/cart/cart',
    })
  },
  // 点击其他信息分组
  infogroupclick: function(e) {
    var that = this;
    var groupposition = e.target.dataset.groupposition;
    var reverse = true;
    reverse = !this.data.otherInfoVos[groupposition].expand;
    this.data.otherInfoVos[groupposition].expand = reverse;
    var copyotherInfoVos = that.data.otherInfoVos
    that.setData({
      otherInfoVos: copyotherInfoVos
    })
  },

  // 点击品牌
  brandClick: function(e) {
    var that = this;
    var itemid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../brandGroup/brandGroup?brandId=' + itemid,
    })

  },
  // 点击设计师
  designerClick: function(e) {
    var that = this;
    var itemid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../designerGroup/designerGroup?designerId=' + itemid,
    })


  },
  // 锚点跳转
  anchor_infor: function() {
    var that = this;
    that.setData({
      product_infos: "product_infos"

    })
  },
  // 点击加入购物车

  addToCart: function() {
    if (app.toLogin()) {
      return
    }
    this.slideUp.call(this)
  },
  //点击立即购买
  buyNow: function() {
    if (app.toLogin()) {
      return
    }
    var params = {
      productId: this.data.productId,
      productQty: this.data.addProductNumber
    }
    wx.navigateTo({
      url: '../order/editOrder/editOrder?productId=' + this.data.productId +
        '&productQty=' + this.data.addProductNumber
    })
  },

  // 点击推荐搭配的子项
  matchproductclick: function(e) {
    var that = this;
    var productId = e.currentTarget.dataset.productid;

    wx.navigateTo({
      url: '../product/productDetail?productId=' + productId,
    })
  },
  // 点击推荐商品子项
  toDetailsTap: function(e) {
    var id = e.currentTarget.dataset.productid;
    wx.navigateTo({
      url: '../product/productDetail?productId=' + id,
    })
  },

  // 隐藏遮罩层  
  hideStandardWindow: function() {
    this.slideDown.call(this)
  },

  // 点击规格
  standardItemClick: function(e) {
    var standardName = e.target.dataset.name;
    var index = e.target.dataset.index;
    var parentindex = e.target.dataset.parentindex;
    var checked = e.target.dataset.checked;
    this.data.utilAttributes[parentindex]
    this.data.standardNames[parentindex] = standardName
    /**
     * getDetailSpecificTasK是获取规格弹窗信息网络任务
     * 本来是要在频繁点击规格的时候先停止之前发起请求但是没有请求结束的任务
     * 然而发现没什么卵用
     */
    if (typeof(this.data.getDetailSpecificTasK) != "undefined") {
      this.data.getDetailSpecificTasK.abort()
    }
    this.resetStandardChecked(parentindex, index, checked)
  },
  // 点击规格减号
  tvSub: function() {
    var addNumber = this.data.addProductNumber
    var colorSub = "#000000"
    var colorAdd = "#000000"
      --addNumber
    if (addNumber <= 1) {
      addNumber = 1
      colorSub = "#cccccc"
    } else {
      colorSub = "#000000"
    }
    if (addNumber < this.data.availableStock) {
      colorAdd = "#000000"
    } else {
      colorAdd = "#cccccc"

    }
    this.setData({
      addProductNumber: addNumber,
      subColor: colorSub,
      addColor: colorAdd,
    })
  },

  // 点击规格加号
  tvAdd: function() {
    var addNumber = this.data.addProductNumber
    var colorAdd = "#000000"
    var colorSub = "#000000"

      ++addNumber
    if (addNumber >= this.data.availableStock) {
      colorAdd = "#cccccc"
      if (this.data.availableStock == 0) {
        addNumber = 1
      } else {
        addNumber = this.data.availableStock
      }
    } else {
      colorAdd = "#000000"
    }
    if (addNumber > 1) {
      colorSub = "#000000"
    } else {
      colorSub = "#cccccc"
    }
    this.setData({
      addProductNumber: addNumber,
      addColor: colorAdd,
      subColor: colorSub
    })
  },

  // 点击确定
  confirm: function(e) {
    var that = this
    if (that.data.addCartAble) {
      if (!that.data.standardChooseAll) {
        that.wetoast.toast({
          title: that.data.standardChooseTip,
        })
        return
      }
      that.postAddToCart()
    }
  },

  // 重置当前选中的规格组的选中状态并把自己的状态反选
  resetStandardChecked: function(parentindex, index, checked) {
    var newutilAttributes = this.data.utilAttributes
    for (var i = 0; i < newutilAttributes[parentindex].length; i++) {
      newutilAttributes[parentindex][i].checked = false
    }

    newutilAttributes[parentindex][index].checked = !checked
    this.setData({
      utilAttributes: newutilAttributes
    })
    // 如果把自己反选了名字置空

    if (checked) {
      this.data.standardNames[parentindex] = ""
    }
    this.resetState(newutilAttributes)
  },


  // 重置规格的库存状态
  resetState: function(newutilAttributes) {

    for (var i = 0; i < newutilAttributes.length; i++) {

      for (var x = 0; x < newutilAttributes[i].length; x++) {
        newutilAttributes[i][x].state = false
      }

    }

    for (var i = 0; i < this.data.standardNames.length; i++) {
      // 这个是选中的规格名字
      var name = this.data.standardNames[i]

      var newSpecificList = []
      for (var j = 0; j < this.data.products.length; j++) {

        // 这个是sku列表的规格名字
        var skuName = this.data.products[j].itemAttrIdPairVoList[i].attributeValueId

        // 筛选出包含选中规格名字的sku
        if (name == skuName) {

          newSpecificList.push(this.data.products[j])
        }

      }

      // 根据选中的规格名判断其他规格在newSpecificList的库存状态
      for (var y = 0; y < newutilAttributes.length; y++) {

        if (y == i) {
          continue;
        } else {
          for (var x = 0; x < newutilAttributes[y].length; x++) {
            var attrName = newutilAttributes[y][x].name.attributeValueId
            var attrState = newutilAttributes[y][x].state

            for (var z = 0; z < newSpecificList.length; z++) {
              if (attrName == newSpecificList[z].itemAttrIdPairVoList[y].attributeValueId) {
                newutilAttributes[y][x].state = false
                break
              } else {
                newutilAttributes[y][x].state = true
              }
            }
          }
        }
      }
    }
    // 参数是为了少执行setData传的
    this.getProduct(newutilAttributes);
  },

  // 获取筛选后的产品和重置规格的库存状态分开写了（可以写在一起）
  getProduct: function(newutilAttributes) {
    var skulist = []
    skulist = skulist.concat(this.data.products)

    for (var i = 0; i < this.data.standardNames.length; i++) {
      var name = this.data.standardNames[i]
      if (name.length == 0) {
        var tip = "请选择" + this.data.attributes[i].attributeName
        this.setData({
          standardChooseAll: false,
          standardChooseTip: tip,
          utilAttributes: newutilAttributes
        })
        return
      }
      for (var j = 0; j < this.data.products.length; j++) {
        var productName = this.data.products[j].itemAttrIdPairVoList[i].attributeValueId
        var productId = this.data.products[j].productItemId
        if (name != productName) {
          out: for (var x = 0; x < skulist.length; x++) {
            if (productId == skulist[x].productItemId) {
              skulist.splice(x, 1);
              break out;
            }
          }
        }
      }
    }

    this.setData({
      productId: skulist[0].productItemId,
      addProductNumber: 1,
      standardChooseAll: true,
      utilAttributes: newutilAttributes
    })

    // 规格弹窗信息

    this.getDetailSpecific(this.data.productId)
  },

  // 添加商品到购物车
  postAddToCart: function() {
    var that = this;
    if (this.data.addProductNumber <= 0) {
      that.wetoast.toast({
        title: '商品数量不正确',
      })
    }
    var params = {
      productId: this.data.productId,
      productQty: this.data.addProductNumber
    }
    var productsInCart = this.data.productQtyInCart + this.data.addProductNumber
    request.post_addToCart(params, (res) => {
      if (res.resCode == 0) {
        that.wetoast.toast({
          title: '加入购物车成功',
        })
        that.setData({
          productQtyInCart: productsInCart
        })
        app.setProductQtyInCart(productsInCart)

      } else {
        that.wetoast.toast({
          title: '加入购物车失败',
        })
      }
      that.slideDown.call(that)

    }, (res) => {
      if (util.alertNetworkError(res)) {
        that.wetoast.toast({
          title: res.resMsg,
        })
      }
    }, {})
  },

  backToHome: function() {
    wx.reLaunch({
      url: '../../pages/home/home',
    })
  },

  imageLoad: function(e) {
    var imageUrl = e.target.dataset.url
    if (imageUrl.indexOf("Text") < 0) {
      this.setData({
        imgheight: 562,
      })
      return
    }
    var index = imageUrl.lastIndexOf("_")

    var secIndex = imageUrl.lastIndexOf("x")
    var thirdIndex = imageUrl.lastIndexOf(".")
    var width = imageUrl.substring(index + 1, secIndex)
    var height = imageUrl.substring(secIndex + 1, thirdIndex)


    //宽高比  
    ratio = width / height;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    this.setData({
      imgheight: viewHeight,
    })
  },
  /**
   * 其他信息包装
   */
  packOtherInfos: function(res) {
    var that = this;
    var copyotherInfoVos = []

    if (res.data.itemOtherInfoList != null) {
      for (var i = 0; i < res.data.itemOtherInfoList.length; i++) {
        res.data.itemOtherInfoList[i].expand = true
      }

      copyotherInfoVos = copyotherInfoVos.concat(res.data.itemOtherInfoList)
    }
    if (res.data.itemCerts != null) {
      copyotherInfoVos.push({
        contentType: 3,
        title: "相关证书",
        expand: true,
        certifications: res.data.itemCerts
      })
    }
    // copyotherInfoVos.push({ contentType: 4, title: "服务承诺", expand: true })
    copyotherInfoVos.push({
      contentType: 5,
      title: "温馨提示",
      expand: true,
      priceExplain: that.data.priceExplain
    })
    copyotherInfoVos.push({
      contentType: 5,
      title: "价格说明",
      expand: true,
      priceExplain: ["划线价格：划线的价格可能是商品的专柜价、吊牌价、正品零售价、指导价、曾经展示过的销售价等，仅供您参考。", "未划线价格：未划线的价格是商品的销售标价，具体的成交价格可能因会员使用优惠券、积分等发生变化，最终以订单结算价格为准。", "*此说明仅当出现价格比较时有效。若这件商品针对划线价格进行了特殊说明，以特殊说明为准。"]
    })
    return copyotherInfoVos;
  },

  // 判断是否有sologan
  isHaveSoloGan: function(res) {
    var that = this;
    if (res.data.sellingPoint && res.data.sellingPointImgUrl) {
      return true;
    } else {
      return false;
    }
  },
  /**
   * 获取详情页规格弹窗
   */
  getDetailSpecific: function(productId) {
    var that = this
    const getDetailSpecificTasK = request.getDetailSpecific(productId, (res) => {
      var imageWidth = util.rpx2px(180)
      var hasStock = res.data.stockQty > 0
      wx.setNavigationBarTitle({
        title: res.data.productTitle
      })

      if (that.data.productId != res.data.productItemId) {
        return
      }

      if (!!res.data.sizeText && !!res.data.netWeightText) {
        that.setData({
          standard_image: res.data.productImage + '?imageMogr2/strip/thumbnail/' + imageWidth + 'x',
          productTitle: res.data.productTitle,
          sellPrice: res.data.sellPrice,
          originalPrice: res.data.originalPrice,
          sizeText: res.data.sizeText,
          netWeightText: res.data.netWeightText,
          inRedemption: res.data.inRedemption,
          stockQty: res.data.stockQty,
          hasStock: hasStock,
          availableStock: res.data.stockQty,
          standard_size: "尺寸:" + res.data.sizeText + " 重量:" + res.data.netWeightText
        })
      } else {
        that.setData({
          standard_image: res.data.productImage + '?imageMogr2/strip/thumbnail/' + imageWidth + 'x',
          productTitle: res.data.productTitle,
          sellPrice: res.data.sellPrice,
          originalPrice: res.data.originalPrice,
          sizeText: res.data.sizeText,
          netWeightText: res.data.netWeightText,
          inRedemption: res.data.inRedemption,
          stockQty: res.data.stockQty,
          hasStock: hasStock,
          availableStock: res.data.stockQty,
        })
      }
      that.showPopupButton()
    }, (error) => {
      if (util.alertNetworkError(error)) {
        that.wetoast.toast({
          title: error.resMsg,
        })
      }
    }, {})
    that.setData({
      getDetailSpecificTasK: getDetailSpecificTasK
    })
  },
  /**
   * 详情页基本信息
   */
  getDetailBaseInfo: function(productId) {
    var that = this
    request.getDetailBaseInfo(productId, (res) => {
        that.setData({
          productAdditionalImgs: res.data.productImages,
          availableStock: res.data.stockQty,
          'product.productTitle': res.data.productTitle,
          'product.sellingPoint': res.data.sellingPoint,
          'product.productId': res.data.productItemId,
          'product.productStatus': res.data.productStatus, // 1已上架2已下架
          'product.productType': res.data.productType,
          'product.userBuyConstraint': res.data.userBuyConstraint,

        })
        that.showPopupButton()

      },
      (error) => {
        if (util.alertNetworkError(error)) {
          that.wetoast.toast({
            title: error.resMsg,
          })
        }
      }, {

      })
  },
  /**
   * 获取详情页sku活动信息
   */
  getDetailSkuInfos: function(productId) {
    var that = this
    request.getDetailSkuInfos(productId, (res) => {
      that.setData({
        'product.sellPrice': res.data.sellPrice,
        'product.originalPrice': res.data.originalPrice,
        'product.itemPromInfoList': res.data.itemPromInfoList,
        'product.skuAttrPairs': res.data.skuAttrPairs,
        'product.productItemId': res.data.productItemId,
        'product.stockQty': res.data.stockQty
      })
    }, (error) => {
      if (util.alertNetworkError(error)) {
        that.wetoast.toast({
          title: error.resMsg,
        })
      }
    }, {})
  },
  /**
   * 展示弹窗底部按钮
   */
  showPopupButton: function() {
    switch (this.data.productStatus) {
      case 1:
        if (this.data.hasStock) {
          this.setData({
            productStockTip: "确定",
            addCartColor: "#FFD444",
            addCartAble: true,
            addColor: "#000000"
          })
        } else {
          this.setData({
            productStockTip: "已售罄",
            addCartColor: "#CCCCCC",
            addCartAble: false

          })
        }
        break
      case 2:
        this.setData({
          productStockTip: "已下架",
          addCartColor: "#CCCCCC",
          addCartAble: false

        })
        break
    }
  },

})